package com.example.filedownandjson.controller.music;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class DownLoading {
    @RequestMapping(value = "/downloadLocal")
    public void downloadLocal(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("fileName");
        String mimeType = request.getParameter("mimeType");
        String type = request.getParameter("type");
        // 读到流中
        InputStream inputStream = new FileInputStream("D:/Music/" + name + "." + type);// 文件的存放路径
        response.reset();
        response.setContentType(mimeType);
        String filename = name + "." + type;
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}